package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/*
*  美团圈圈中间件
* */
@Slf4j
public class Plugin_ECARD_P031 implements ChannelService {

    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {
        try {
            String accountVal = String.valueOf(data.get("AccountVal"));
            if (Pattern.matches("^1[3456789]\\d{9}$", accountVal) != true) {
                return  ChannelResult.error("手机号码异常");
            }
            HashMap<String, String> resParams = new HashMap<>();
            resParams.put("app_id",apiConfig.getString("AppId"));
            resParams.put("order_no",String.valueOf(data.get("ChannelOrderCode")));
            resParams.put("mobile",accountVal);
            resParams.put("coupon_id",String.valueOf(data.get("SUPProductId")));//券批次号
            String key = apiConfig.getString("SecretKey");
            String submitUrl = apiConfig.getString("SubmitUrl");
            String sign = generateSign(resParams, key);
            resParams.put("sign",sign);
            String res = HttpTool.sendPost(submitUrl, resParams);
            JSONObject resObj = JSONObject.parseObject(res);
            String code = resObj.getString("code");
            String message = resObj.getString("message");
            if (code.equals("200")) {
                JSONObject encryptData = resObj.getJSONObject("encryptData");
                String couponStatus = encryptData.getString("couponStatus");
                if (couponStatus.equals("0")) {
                    return ChannelResult.success("充值成功");
                }
                return ChannelResult.IN_PROCESS("充值中");
            }
            if (code.equals("1007")) {//重复订单
                return ChannelResult.IN_PROCESS("充值中");
            }
            if (code.equals("1005")|| code.equals("1100") || code.equals("1003")){
                return ChannelResult.FAILED(message);
            }
            return ChannelResult.error(message);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("美团圈圈提交订单接口错误：",e);
            return  ChannelResult.error("美团圈圈提交订单接口错误");
        }
    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {
        try {
            HashMap<String, String> resParams = new HashMap<>();
            resParams.put("app_id",apiConfig.getString("AppId"));
            resParams.put("order_no",String.valueOf(data.get("ChannelOrderCode")));
            resParams.put("mobile",String.valueOf(data.get("AccountVal")));
            resParams.put("coupon_id",String.valueOf(data.get("SUPProductId")));//券批次号
            String key = apiConfig.getString("SecretKey");
            String queryUrl = apiConfig.getString("QueryUrl");
            String sign = generateSign(resParams, key);
            resParams.put("sign",sign);
            String res = HttpTool.sendPost(queryUrl, resParams);
            JSONObject resObj = JSONObject.parseObject(res);
            String code = resObj.getString("code");
            String message = resObj.getString("message");

            if (code.equals("200")) {
                JSONObject encryptData = resObj.getJSONObject("encryptData");
               // JSONObject encryptData = resObj.getObject("encryptData", JSONObject.class);
                //⽤户券状态 0-未使⽤ 20-发劵挂起中 80-已使⽤ 81-已作废 82-未⽣效 83-已过期
                String couponStatus = encryptData.getString("couponStatus");
                if (couponStatus.equals("20")) {
                    return ChannelResult.IN_PROCESS("发券挂起中");
                }else if (couponStatus.equals("81")){
                    return ChannelResult.FAILED("卡券已作废");
                }
                return ChannelResult.success("充值成功");
            }
            if (code.equals("4003")) {
                return ChannelResult.FAILED(message);
            }
            return ChannelResult.error(message);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("美团圈圈查询订单接口错误：",e);
            return  ChannelResult.error("美团圈圈查询订单接口错误");
        }

    }

    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return ChannelResult.success("success");
    }

    public static String generateSign(Map<String, String> params,String apiKey) {
        // 先对map的键进行排序
        String result = params.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(entry -> entry.getKey() + entry.getValue())
                .collect(Collectors.joining());

        // 添加API Key
        result += apiKey;

        // 计算MD5值
        return md5(result);
    }

    public static String md5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(s.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
            }
            return sb.toString().toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


}
